<template>
  <el-form ref="loginFormRef" :model="loginForm" :rules="loginRules" size="large">
    <el-form-item prop="userName">
      <el-input v-model="loginForm.username" placeholder="请输入工号/用户名/手机号">
        <template #prefix>
          <el-icon class="el-input__icon">
            <user />
          </el-icon>
        </template>
      </el-input>
    </el-form-item>
    <el-form-item prop="password">
      <el-input v-model="loginForm.password" type="password" placeholder="请输入密码" show-password autocomplete="new-password">
        <template #prefix>
          <el-icon class="el-input__icon">
            <lock />
          </el-icon>
        </template>
      </el-input>
    </el-form-item>
    <!-- <el-form-item prop="code">
      <el-input v-model="loginForm.code" placeholder="验证码" style="width: 60%">
        <template #prefix>
          <el-icon class="el-input__icon">
            <img style="width: 100%; height: 100%" src="/src/assets/icons/validCode.svg" />
          </el-icon>
        </template>
      </el-input>
      <div class="login-code">
        <img :src="codeUrl" @click="getCodeHandler" class="login-code-img" />
      </div>
    </el-form-item> -->
  </el-form>
  <div class="login-btn">
    <el-button
      :icon="UserFilled"
      size="large"
      type="primary"
      :loading="loading"
      @click="loginHandler(loginFormRef)"
      style="width: 100%"
    >
      登 录
    </el-button>
  </div>
</template>

<script setup lang="ts">
import type { LoginForm } from "@/typings";
import type { FormRules, FormInstance } from "element-plus";
import { ElMessage, ElNotification } from "element-plus";
import { initDynamicRouter } from "@/routers/modules/dynamicRouter";
import { ref, reactive, onMounted } from "vue";
import { User, UserFilled } from "@element-plus/icons-vue";
import { useKeepAliveStore, useTabsStore, useUserStore, usePermissionStore, useGlobalStore } from "@/stores";
import { login, getInfoApi } from "@/api";
import { HOME_URL, SALUTATION } from "@/config";
import { useRouter } from "vue-router";
import { getTimeState, random } from "@/utils";
import md5 from "md5";
import { useTheme } from "@/hooks/useTheme";

const loginFormRef = ref<FormInstance>();
const loading = ref(false);
const router = useRouter();
const useUser = useUserStore();
const useTabs = useTabsStore();
const useKeepAlive = useKeepAliveStore();
const usePermission = usePermissionStore();
const useThemeStore = useTheme();
// const codeUrl = ref("");
const loginForm: LoginForm = reactive({
  username: "",
  password: ""
});
const loginRules: FormRules<typeof loginForm> = reactive({
  username: [
    { required: true, message: "用户名称不能为空!", trigger: "blur" },
    { min: 4, max: 16, message: "长度为 4 ~ 16 位!", trigger: "blur" }
  ],
  password: [
    { required: true, message: "用户密不能为空!", trigger: "blur" },
    { min: 6, max: 16, message: "密码的长度为 6 ~ 16 位!", trigger: "blur" }
  ],
  code: [{ required: true, message: "验证码不能为空!", trigger: "blur" }]
});

/**
 * @description 登录处理
 * @param formEl 表单实例
 */
const loginHandler = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate(async (valid: boolean) => {
    if (!valid) return;
    loading.value = true;
    try {
      const params = {
        username: loginForm.username,
        password: loginForm.password
      };
      params.password = md5(params.password);
      const loginResult = await login({ ...params });
      if (loginResult.code === 200) {
        ElMessage.success("登录成功");
        const { data } = loginResult;
        useUser.token = data as any;
        router.push(HOME_URL);
        const userInfoData = await getInfoApi();
        if (userInfoData.code === 200) {
          const { permissions, role, user, config } = userInfoData.data as any;
          useUser.userInfo = user;
          usePermission.permissions = permissions;
          if (config) {
            config.isDark = config.isDark === "0" ? true : false;
            config.isCollapse = config.isCollapse === "0" ? true : false;
            config.breadcrumb = config.breadcrumb === "0" ? true : false;
            config.breadcrumbIcon = config.breadcrumbIcon === "0" ? true : false;
            config.tabs = config.tabs === "0" ? true : false;
            config.tabsIcon = config.tabsIcon === "0" ? true : false;
            Object.assign(useGlobalStore().globalConfig, config);
            useThemeStore.changePrimary(config.sysPrimary);
            useThemeStore.changeMenuPrimary(config.menuPrimary);
            useThemeStore.initTheme();
          }
          sessionStorage.setItem("role", JSON.stringify(role));
        } else {
          ElMessage.error(userInfoData.message);
        }
        await initDynamicRouter();
        useTabs.closeMultipleTab();
        useKeepAlive.setKeepAliveName();
        ElNotification({
          title: "哈喽，" + useUser.userInfo?.userName + getTimeState(),
          message: SALUTATION[random(0, SALUTATION.length - 1)],
          type: "success",
          duration: 5000
        });
        return false;
      } else {
        ElMessage.error(loginResult.message);
      }
      // // todo 判断验证码错误的时候从新刷新验证码
      // ElMessage.error(loginResult.message);
    } catch (error) {
      ElMessage.error("登录失败，请稍后再试!");
    } finally {
      loading.value = false;
    }
  });
};

/**
 * @description 获取验证码
 */
// const getCodeHandler = async () => {
//   const result = await getCode();
//   codeUrl.value = `data:image/gif;base64,${result.data.img}`;
//   // loginForm.uuid = result.data.uuid;
// };

onMounted(async () => {
  // await getCodeHandler();
  document.onkeydown = (e: KeyboardEvent) => {
    e = (window.event as KeyboardEvent) || e;
    if (e.code === "Enter" || e.code === "enter" || e.code === "NumpadEnter") {
      if (loading.value) return;
      loginHandler(loginFormRef.value);
    }
  };
});
</script>

<style scoped lang="scss">
@import "../index.scss";

.login-code {
  width: 40%;
  height: 38px;
  display: flex;
  align-items: center;
  justify-content: center;
  .login-code-img {
    cursor: pointer;
    height: 100%;
    vertical-align: middle;
  }
}
</style>
